package com.example.myapplication.ui.fragment

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.bean.article.BannerBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.example.myapplication.ui.vm.SharedViewModel
import com.kun.base.env.Env
import com.kun.base.ui.AbsBaseFragment
import com.scwang.smart.refresh.header.ClassicsHeader
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 * 首页
 *  @author : MyPC
 *  @date : 2021/4/14
 *  @time : 10:37
 */
class HomeFragment : AbsBaseFragment() {
    private var index = 0
    private lateinit var articleAdapter: ArticleAdapter

    private lateinit var homeViewModel: HomeViewModel
    private lateinit var sharedViewModel: SharedViewModel

    private var banner: Banner<BannerBean, BannerImageAdapter<BannerBean>>? = null

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun initViewModel() {
        homeViewModel = getActivityScopeViewModel(HomeViewModel::class.java)
        sharedViewModel = getApplicationScopeViewModel(SharedViewModel::class.java)
        sharedViewModel.userdata.observe(this, Observer {
            refresh_layout!!.autoRefresh()
        })
        sharedViewModel.unCollectArticle.observe(this, Observer { t ->
            articleAdapter.let {
                val list = it.data
                for (i in list) {
                    if (t == i.id) {
                        i.collect = false
                    }
                }
                it.notifyDataSetChanged()
            }
        })
        initArticleResult()
        initBannerResult()
        initTopArticleResult()
        initAddCollectArticle()
        initDelCollectArticle()
    }

    override fun initView() {
        iv_back.visibility = View.GONE
        iv_close.visibility=View.VISIBLE
        iv_close.setBackgroundResource(R.drawable.search)
        iv_close.setOnClickListener {
            ARouter.getInstance().build(ARouterPath.SEARCH).navigation()
        }

        refresh_layout!!.setRefreshHeader(ClassicsHeader(activity))

        //头部banner
        val view = View.inflate(activity, R.layout.list_article_header, null)
        banner =
            view.findViewById(R.id.banner)
        banner!!.addBannerLifecycleObserver(this)
            .setIndicator(CircleIndicator(activity))
            .setBannerRound(20f)

        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.addHeaderView(view)
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        recycler_view!!.layoutManager = LinearLayoutManager(activity)
        recycler_view!!.adapter = articleAdapter

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            getBanner()
            getTopArticleList()
        }
        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }
        articleAdapter.addChildClickViewIds(R.id.view_collect)
        articleAdapter.setOnItemChildClickListener { _, childView, position ->
            val articleBean = articleAdapter.getItem(position)
            if (childView.id == R.id.view_collect) {
                if (articleBean.collect) {
                    homeViewModel.requestDelCollectArticle(articleBean.id)
                } else {
                    homeViewModel.requestAddCollectArticle(articleBean.id)
                }
            }
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true

        }
        getBanner()
        getTopArticleList()
    }

    /**
     * 加载文章列表
     */
    private fun getData() {
        homeViewModel.requestArticleList(index)
    }

    /**
     * 加载banner
     */
    private fun getBanner() {
        homeViewModel.requestBannerList()
    }

    /**
     * 加载置顶文章
     */
    private fun getTopArticleList() {
        homeViewModel.requestTopArticleList()
    }

    /**
     *文章列表接口返回结果
     */
    private fun initArticleResult() {
        homeViewModel.articleRequest.articleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
//                if (t.data!!.curPage == 0) {
//                    articleAdapter.setList(t.data!!.datas)
//                } else {
                    articleAdapter.addData(t.data!!.datas)
//                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    articleAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    articleAdapter.loadMoreModule.loadMoreComplete()
                }
            }else {
                articleAdapter.loadMoreModule.loadMoreComplete()
            }
            refresh_layout!!.finishRefresh()

        })
    }

    /**
     * banner数据返回结果
     */
    private fun initBannerResult() {

        homeViewModel.articleRequest.bannerListResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                banner!!.setAdapter(object : BannerImageAdapter<BannerBean>(t.data) {
                    override fun onBindView(
                        holder: BannerImageHolder,
                        data: BannerBean,
                        position: Int,
                        size: Int
                    ) {
                        Glide.with(holder.itemView)
                            .load(data.imagePath)
                            .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                            .into(holder.imageView)
                        holder.itemView.setOnClickListener {
                            startToWeb(data.url, data.title)
                        }
                    }
                })
            }
        })
    }

    /**
     *置顶文章数据返回结果
     */
    private fun initTopArticleResult() {
        homeViewModel.articleRequest.topArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                val topArticleList = t.data
                for (article in topArticleList!!) {
                    article.isTop = true
                }
                articleAdapter.setList(topArticleList)

                index = 0
                getData()
            }
        })
    }

    /**
     * 收藏文章接口回调
     */
    private fun initAddCollectArticle() {
        homeViewModel.collectRequest.addArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = true
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        homeViewModel.collectRequest.delArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = false
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(activity!!).apply {
            addSelectItems("打开链接", if (articleBean.collect) "取消收藏" else "收藏")
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else {
                        if (articleBean.collect) {
                            homeViewModel.requestDelCollectArticle(articleBean.id)
                        } else {
                            homeViewModel.requestAddCollectArticle(articleBean.id)
                        }
                    }
                    dismiss()
                }
            })
        }.show()
    }
}